package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class liyshApplicationContext {
    private Class configClass;

    private ConcurrentHashMap<String,Object> singletonObjects = new ConcurrentHashMap<>();   //单例池(一级缓存)

    private ConcurrentHashMap<String,BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>();   //存bean的定义

    private List<BeanPostProcessor> beanPostProcessorsList = new ArrayList<>();
    //构造容器
    public liyshApplicationContext(Class configClass){
        this.configClass = configClass;
        //解析配置类
        //ComponentScan注解--->扫描路径-->扫描-->Beandefinition-->BeanDefinitionMap
        scan(configClass);
        for (Map.Entry<String,BeanDefinition> entry : beanDefinitionMap.entrySet()) {
            String beanName = entry.getKey();
            BeanDefinition beanDefinition = entry.getValue();
            if(beanDefinition.getScope().equals("singleton")){
                Object bean = createBean(beanName,beanDefinition); //单例bean
                singletonObjects.put(beanName,bean);
            }
        }
    }

    public Object createBean(String beanName, BeanDefinition beanDefinition){
        Class clazz = beanDefinition.getClazz();
        try{
            //实例化bean对象
            Object instance = clazz.getDeclaredConstructor().newInstance();
            //对属性依赖注入
            for (Field declaredField : clazz.getDeclaredFields()) {
                if(declaredField.isAnnotationPresent(Autowired.class)){
                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance,bean);
                }
            }
            //Aware回调
            if(instance instanceof BeanNameAware){
                ((BeanNameAware)instance).setBeanName(beanName);
            }
            //BeanPostProcessor:初始化之前
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
                instance= beanPostProcessor.postProcessBeforeInitialization(instance,beanName);
            }
            //初始化
            if(instance instanceof InitializingBean){
                try {
                    ((InitializingBean)instance).afterPropertiesSet();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            //BeanPostProcessor:初始化后做一些操作 比如AOP
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
                instance= beanPostProcessor.postProcessAfterInitialization(instance,beanName);
            }
            return instance;
        }catch(InstantiationException e){
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }catch (InvocationTargetException e){
            e.printStackTrace();
        }catch (NoSuchMethodException e){
            e.printStackTrace();
        }
        return null;
    }
    private void scan(Class configClass) {
        ComponentScan componentScanAnnotation=(ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        String path= componentScanAnnotation.value();//扫描路径com.liysh.service
        path = path.replace(".","/");
        //Bootstrap-------->jre/lib
        //Ext---------->jre/ext/lib
        //App-------->classpath------>
        ClassLoader classLoader = liyshApplicationContext.class.getClassLoader();  //app
        URL resource =classLoader.getResource(path);
        File file = new File(resource.getFile());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(File f:files){
                String fileName = f.getAbsolutePath();  //E:\work\SpringByMySelf\target\classes\com\liysh\service\UserService.class
                if(fileName.endsWith(".class")){
                    String className = fileName.substring(fileName.indexOf("com"),fileName.indexOf(".class"));
                    className = className.replace("\\","."); //com.liysh.service.UserService
                    try{
                        Class<?> clazz = classLoader.loadClass(className);
                        if(clazz.isAnnotationPresent(Component.class)){
                            //表示当前这个类是一个Bean
                            //解析类-->BeanDefinition，实际上是为了把判断当前bean是单例bean，还是prototype的bean，等类的信息封装    暂时不区分懒加载
                            // BeanDefinition   bean的定义
                            if(BeanPostProcessor.class.isAssignableFrom(clazz)){
                                BeanPostProcessor instance = (BeanPostProcessor)clazz.getDeclaredConstructor().newInstance();
                                beanPostProcessorsList.add(instance);
                            }
                            Component componentAnnotation = clazz.getDeclaredAnnotation(Component.class);
                            String beanName = componentAnnotation.value();
                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setClazz(clazz);
                            if(clazz.isAnnotationPresent(Scope.class)){
                                Scope scopeAnnotation = clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinition.setScope(scopeAnnotation.value());
                            }else{
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    }catch(ClassNotFoundException | NoSuchMethodException e){
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }

    public Object getBean(String beanName){
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if(beanDefinitionMap.containsKey(beanName)){
            if(beanDefinition.getScope().equals("singleton")){
                Object o = singletonObjects.get(beanName);
                return o;
            }else{
                //创建Bean对象
                Object bean = createBean(beanName,beanDefinition);
                return bean;
            }
        }else{
            //不存在对应的Bean
            throw new NullPointerException();
        }
    }
}
